<?php

namespace App\Http\Controllers\Members\MembersRealname;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Repositories\MembersRealnameRepository as RealnameRepository;
use Storage;
/**
* 会员实名认证
*/
class IndexController extends Controller
{
    public function __construct()
		{
			$this->middleware('auth:members');
		}
		public function Save(Request $request,RealnameRepository $RealnameRepository)
		{
			$user = auth('members')->user();
			$model=$RealnameRepository->findBy('MembersID',$user->ID);
			if(empty($model))
			{
				$RealnameRepository->create(['ID'=>$this->nextid(),'MembersID'=>$user->ID, 'Status'=>0,'CreateTime'=>time()]);
				$model=$RealnameRepository->findBy('MembersID',$user->ID);
			}
			$model->Name=trim($request->input('Name'));
			$model->LinkmanPhone=trim($request->input('LinkmanPhone'));
			$model->CertificatesType=trim($request->input('CertificatesType'));
			$model->CertificateNo=trim($request->input('CertificateNo'));
      $model->save();
      return response()->json(['code' => 0, 'message' => '实名认证资料保存成功！']);
		}
		public function Get(Request $request,RealnameRepository $RealnameRepository)
		{
			$user = auth('members')->user();
			$model=$RealnameRepository->findBy('MembersID',$user->ID);
			if(!empty($model))
			{
				$model->IDface=empty($model->IDface)?'':$this->ToImageURL('/MembersRealname/'.$model->IDface);
				$model->IDback=empty($model->IDback)?'':$this->ToImageURL('/MembersRealname/'.$model->IDback);
			}
			return response()->json(['code' => 0, 'message' => 'OK！', 'result' => $model]);
		}
		public function UploadImg($field,Request $request, RealnameRepository $RealnameRepository)
	 {
		 	$user = auth('members')->user();
			$model=$RealnameRepository->findBy('MembersID',$user->ID);
			if(empty($model))
			{
				$RealnameRepository->create(['ID'=>$this->nextid(),'MembersID'=>$user->ID, 'Status'=>0,'CreateTime'=>time()]);
				$model=$RealnameRepository->findBy('MembersID',$user->ID);
			}
			
		 if ($request->hasFile('file')) {

			$file = $request->file('file');
 
			$ext = $file->getClientOriginalExtension(); 
			$realPath = $file->getRealPath();  
		 
			$filename = uniqid() . '.' . $ext;
			if (in_array(strtolower($file->extension()), ['jpeg', 'jpg', 'gif', 'gpeg', 'png'])) {
				 
				$bool = Storage::disk('oss')->put("/MembersRealname/" . $filename, file_get_contents($realPath));
				 
				if (!$bool) {
					return response()->json(['code' => 1, 'message' => '上传失败']);
				}
				else {
					if (trim( $model[$field]) != '') {
						 
						Storage::disk('oss')->delete("/MembersRealname/" . $model[$field]);
					}
					$model->$field=$filename;
				  $model->save();
					return response()->json(['code' => 0, 'message' => '图片上传成功！', 'result' => $filename]);
				}
			}
			else {
				return response()->json(['code' => 1, 'message' => '请选择图片文件']);
			}
		}

	}
}
